package com.wsg.lightaccounting.Fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.wsg.lightaccounting.Adapter.DateSumListAdapte;
import com.wsg.lightaccounting.ClassConversion;
import com.wsg.lightaccounting.DB.DB;
import com.wsg.lightaccounting.Model.RecordManager;
import com.wsg.lightaccounting.R;

import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link LineFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link LineFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LineFragment extends Fragment {
    private LineChart lineChart;
    private ListView listView;
    private DateSumListAdapte dateSumListAdapte;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public static String UPDATEUI_LINE_FRAGMENT = "update UI in line fragment";

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(UPDATEUI_LINE_FRAGMENT)){
                updateUI();
            }
        }
    };

    public LineFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment LineFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static LineFragment newInstance(String param1, String param2) {
        LineFragment fragment = new LineFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UPDATEUI_LINE_FRAGMENT);
        getActivity().registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_line, container, false);
        initView(view);
        return view;
    }
    private void initView(View view){
        lineChart = (LineChart) view.findViewById(R.id.line_chart);
        lineChart.setData(getLineData());
        listView = (ListView) view.findViewById(R.id.line_fragment_list);
        dateSumListAdapte = new DateSumListAdapte(getActivity(),RecordManager.getRecordManager(getActivity()).getDataSums());
        listView.setAdapter(dateSumListAdapte);
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
       updateUI();
    }
    public void updateUI(){
        dateSumListAdapte.setDateSa(RecordManager.getRecordManager(getActivity()).getDataSums());
        dateSumListAdapte.notifyDataSetChanged();
        lineChart.setData(getLineData());
        lineChart.animateX(2000);
    }
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }
    private LineData getLineData(){
        Calendar rightNow = Calendar.getInstance();
        java.util.Date date = new Date(System.currentTimeMillis());
        float[][] sevenSum = RecordManager.getRecordManager(getActivity()).getSevenDateSum(date);

        ArrayList<String> xVals = new ArrayList<String>();
        for (int i = 0; i < 7; i++) {
            rightNow.setTime(date);
            rightNow.add(Calendar.DAY_OF_YEAR,-i);
            java.util.Date dt1=rightNow.getTime();
            xVals.add(0,ClassConversion.dateToString(dt1,"yyyy-MM-dd"));
        }

        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < 7; i++) {
            yVals1.add(new Entry(sevenSum[0][i],6-i));
        }
        ArrayList<Entry> yVals2 = new ArrayList<Entry>();
        for (int i = 0; i < 7; i++) {
            yVals2.add(new Entry(sevenSum[1][i],6-i));
        }
        LineDataSet set1 = new LineDataSet(yVals1, "近七日的支出情况");
        LineDataSet set2 = new LineDataSet(yVals2,"近七日的收入情况");
        // set1.setFillAlpha(110);
        // set1.setFillColor(Color.RED);

        set1.setLineWidth(1.75f); // 线宽
        set1.setCircleSize(3f);// 显示的圆形大小
        set1.setColor(Color.RED);// 显示颜色
        set1.setCircleColor(Color.RED);// 圆形的颜色
        set1.setHighLightColor(Color.RED); // 高亮的线的颜色

        set2.setLineWidth(1.75f); // 线宽
        set2.setCircleSize(3f);// 显示的圆形大小
        set2.setColor(Color.GREEN);// 显示颜色
        set2.setCircleColor(Color.GREEN);// 圆形的颜色
        set2.setHighLightColor(Color.GREEN); // 高亮的线的颜色

        ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
        dataSets.add(set1);// add the datasets
        dataSets.add(set2);

        // create a data object with the datasets
        LineData data = new LineData(xVals, dataSets);
        return data;
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }


    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
